package com.cskaoyan.day03.stack;

/**
 * @author stone
 * @date 2022/01/29 14:50
 */
public class LinkedStack <T>{
    Node top;//head也可以
    int size;

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public boolean push(T value) {
        //将新结点放在top之前
        top = new Node(value, top);
        size++;
        return true;
    }

    public T pop() {
        //如果栈为空，不允许pop
        if (isEmpty()) {
            throw new RuntimeException("栈为空！");
        }
        T value = top.value;
        top = top.next; //头结点后移
        size--;

        return value;
    }

    public T peek() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空！");
        }
        return top.value;
    }

    class Node{
        T value;
        Node next;

        public Node(T value) {
            this.value = value;
        }

        public Node(T value, Node next) {
            this.value = value;
            this.next = next;
        }
    }
}
